# coding:utf-8
"""
@author: jing
@contact: 529548204@qq.com
@file: serializer.py
@time: 2022/5/24 16:56
"""
from rest_framework import serializers
from .models import *


class HeadersSerializers(serializers.ModelSerializer):
    # id = serializers.IntegerField()
    headers_key = serializers.CharField()
    headers_value = serializers.CharField()

    class Meta(object):
        model = Headers
        fields = [
            "headers_key",
            "headers_value"
        ]


class UrlSerializers(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    urls = serializers.CharField(required=True, allow_null=False)
    describe = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    module_id = serializers.IntegerField(required=True, allow_null=False)
    module_name = serializers.SerializerMethodField(read_only=True)
    headers = HeadersSerializers(many=True)

    class Meta(object):
        model = Urls
        fields = "__all__"

    def create(self, validated_data):
        headerlist = validated_data.get('headers')
        validated_data.pop("headers")
        urls = Urls.objects.create(**validated_data)
        for he in headerlist:
            Headers.objects.create(**he, urls_id=urls.id)
        return urls

    def update(self, instance: Urls, validated_data: dict):
        headerslist_data = validated_data.pop("headers")
        headerslist_obj = instance.headers.all()
        instance.urls = validated_data.get("urls", instance.urls)
        instance.module = validated_data.get("module", instance.module)
        instance.describe = validated_data.get("describe", instance.describe)
        instance.url_name = validated_data.get("url_name", instance.url_name)
        instance.save()
        headerslist_obj.delete()
        for hedata in headerslist_data:
            Headers.objects.create(**hedata, urls_id=instance.id)
        return instance

    def validate(self, attrs):
        data = super().validate(attrs)
        url_name = data.get("url_name")
        if not url_name:
            data["url_name"] = data["urls"]
        return data

    @staticmethod
    def get_module_name(obj):
        module_obj = obj.module
        return module_obj.modulename

    def to_representation(self, instance):
        data = super().to_representation(instance)
        return data
